package com.ttx.suite.web.util;

import cn.hutool.core.lang.Assert;
import org.springframework.beans.BeanUtils;
import org.springframework.core.convert.converter.Converter;

import java.util.List;

/**
 * @author
 * @date
 */
public class ConvertUtil {
    public static void copyProps(Object source, Object target){
        Assert.notNull(source,"[source]不能为Null");
        Assert.notNull(target,"[target]不能为Null");
        BeanUtils.copyProperties(source, target);
    }

    /**
     * 使用复制属性转换
     * @param source
     * @param targetClazz
     * @param <S>
     * @param <T>
     * @return
     */
    public static <S,T>  T convert(S source, Class<T> targetClazz){
        T t=null;
        try {
            t=(T)targetClazz.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        BeanUtils.copyProperties(source, t);
        return t;
    }


    /**
     * 默认使用复制属性转换
     * @param source
     * @param target
     * @param targetClazz
     * @param <S>
     * @param <T>
     */
    public static <S,T> void convertList(List<S> source,
                                      List<T> target,
                                      Class<T> targetClazz){
        convertList(source, target, (s)->{
            return convert(s, targetClazz);
        });
    }



    public static <S,T> void convertList(List<S> source,
                                      List<T> target,
                                      Converter<S, T> converter){
        Assert.notNull(source,"[source]不能为Null");
        Assert.notNull(target,"[target]不能为Null");
        source.stream().forEach((s) ->{
            T t=converter.convert(s);
            target.add(t);
        });
    }



}
